package com.xiaode.controller.app.task.activity;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.Activity;
import com.xiaode.common.model.ActivityEnroll;
import com.xiaode.common.model.ActivityUser;
import com.xiaode.common.model.ActivityUserRankingPublic;
import com.xiaode.common.model.Admin;
import com.xiaode.common.model.CampusShareOriginal;
import com.xiaode.common.model.Medal;
import com.xiaode.common.model.MedalUser;
import com.xiaode.common.model.Student;
import com.xiaode.common.model.StudentTrajectory;
import com.xiaode.exce.EnumError;
import com.xiaode.util.UserUtil;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ActivityService {


    /**
     * 分页查询活动列表
     */
    public Ret getActivityPage(Integer accountId, Integer userTypeMy, Boolean haveMe, Integer state, Boolean isExamine, Integer page, Integer limit) throws Exception {
        
    	Page<Activity> activitiePage = new Page<Activity>();
        if(isExamine) {
        	activitiePage = Activity.dao.paginate(page, limit, "SELECT id,publisher_account_id,department,title,files,update_time,end_date ", "FROM activity WHERE is_examine_finish = ? ORDER BY id DESC ", state);       	
        }else {
        	activitiePage = Activity.dao.paginate(page, limit, "SELECT id,publisher_account_id,department,title,files,update_time,end_date ", "FROM activity ORDER BY id DESC ");
        }
        if(activitiePage.getTotalRow() == 0) {
            return Ret.ok().set("activitiePage", activitiePage);
        }
        List<Activity> activitieList = activitiePage.getList();
        
        //如果时学生查询列表，在活动里添加这个学生各个活动的完成情况
        if(haveMe && userTypeMy == Const.UserType.student) {
        	List<Integer> activityIdList = activitieList.stream().map(Activity::getId).collect(Collectors.toList());
            Kv kv = Kv.by("activityIdList", activityIdList).set("accountId", accountId);
            //查询当前用户是否完成活动
            List<Record> records = Db.template("findUserJoinActivityId", kv).find();
            Set<Integer> set = records.stream().map(record -> record.getInt("activity_id")).collect(Collectors.toSet());
            for (Activity activity : activitieList) {
                if (set.contains(activity.getId())) {
                    activity.put("complete", true);
                }
            }
        }
        //在活动里添加发布人信息
        for (Activity activity : activitieList) {
            Integer publisherAccountId = activity.getPublisherAccountId();
            Record rec = Redis.use().hget(Const.user.AccountIdInfo, publisherAccountId);
            Admin ad = Redis.use().get(Const.user.Admin + rec.getInt("id"));
            activity.put("publicUserName", ad.getName());
            activity.put("publicUserType", Const.UserType.admin);
            activity.put("publicUserPic", ad.getAvatarUrl());
            activity.put("publicUserSex", ad.getGender());
        }

        return Ret.ok("activitiePage", activitiePage);
    }

    /**
     * 查询某个学生已审核的活动列表（个人页面）
     */
    public Ret getUserActivityPage(Integer accountId, Integer page, Integer limit) throws Exception {
        Page<Record> activityUserPage = Db.paginate(page, limit, "SELECT id,activity_id ", "FROM activity_user WHERE student_account_id = ? AND evaluate_account_id IS NOT NULL ORDER BY id DESC ", accountId);
        List<Record> activityList = new ArrayList<Record>();
        for (Record activityUser : activityUserPage.getList()) {
            Activity activity = Activity.dao.findById(activityUser.getInt("activity_id"));
            if(BeanUtil.isNotEmpty(activity)){
                Integer publisherAccountId = activity.getPublisherAccountId();
                Record rec = Redis.use().hget(Const.user.AccountIdInfo, publisherAccountId);
                Admin ad = Redis.use().get(Const.user.Admin + rec.getInt("id"));
                activity.put("publicUserName", ad.getName());
                activity.put("publicUserType", Const.UserType.admin);
                activity.put("publicUserPic", ad.getAvatarUrl());
                activity.put("publicUserSex", ad.getGender());

                activityList.add(activity.toRecord());
            }
        }
        activityUserPage.setList(activityList);

        return Ret.ok("activityUserPage", activityUserPage);
    }
    
    /**
     * 查询老师发布的活动列表
     */
    public Ret getActivityPageByPublicer(Integer accountId, Integer page, Integer limit) throws Exception {
    	Page<Activity> activitiePage = Activity.dao.paginate(page, limit, "SELECT id,publisher_account_id,department,title,files,update_time,end_date ", "FROM activity WHERE publisher_account_id = ? ORDER BY id DESC ", accountId);
        if(activitiePage.getTotalRow() == 0) {
            return Ret.ok().set("activitiePage", activitiePage);
        }
        List<Activity> activitieList = activitiePage.getList();
        //在活动里添加发布人信息
        for (Activity activity : activitieList) {
            Integer publisherAccountId = activity.getPublisherAccountId();
            Record rec = Redis.use().hget(Const.user.AccountIdInfo, publisherAccountId);
            Admin ad = Redis.use().get(Const.user.Admin + rec.getInt("id"));
            activity.put("publicUserName", ad.getName());
            activity.put("publicUserType", Const.UserType.admin);
            activity.put("publicUserPic", ad.getAvatarUrl());
            activity.put("publicUserSex", ad.getGender());
        }
        return Ret.ok("activitiePage", activitiePage);
    }
    
    /**
     * 获取活动详情
     */
    public Ret getActivityInfo(Integer activityId) throws Exception {
    	Activity activity = Activity.dao.findById(activityId);
    	if(BeanUtil.isEmpty(activity)){
    		return Ret.fail().set("error", EnumError.ACTIVITY_NULL.getObj());
    	}
    	//查询发布活动人的信息
    	Integer publisherAccountId = activity.getPublisherAccountId();
    	Record rec = Redis.use().hget(Const.user.AccountIdInfo, publisherAccountId);
    	Admin ad = Redis.use().get(Const.user.Admin + rec.getInt("id"));
    	activity.put("publicUserName", ad.getName());
    	activity.put("publicUserType", Const.UserType.admin);
    	activity.put("publicUserPic", ad.getAvatarUrl());
    	activity.put("publicUserSex", ad.getGender());
    	
    	return Ret.ok("activity", activity);
    }
   
    /**
     * 查询某个学生的活动参与情况
     */
    public Ret getActivityUserJoinInfo(Integer activityId, Integer accountId) throws Exception {
    	//先查询报名情况
    	Activity activity = Activity.dao.findById(activityId);
    	if(BeanUtil.isEmpty(activity)){
    		return Ret.fail().set("error", EnumError.ACTIVITY_NULL.getObj());
    	}
    	ActivityUser activityUserInfo = ActivityUser.dao.findFirst("SELECT * FROM activity_user WHERE activity_id = ? AND student_account_id = ?", activityId, accountId);
 		
    	return Ret.ok("activityUserInfo", activityUserInfo);
    }
    
    /**
     * 某个学生活动的报名情况
     */
    public Ret getUserEnrollInfo(Integer activityId, Integer accountId) throws Exception {
    	ActivityEnroll activityEnroll = ActivityEnroll.dao.findFirst("SELECT * FROM activity_enroll WHERE student_account_id = ? AND activity_id = ?", accountId, activityId);
    	return Ret.ok("activityEnroll", activityEnroll);
    }

    /**
     * 发布活动
     */
    public Ret publishActivity(Integer accountId, Integer userType, String title, String content, String department, String files, Integer score, Date endDate, String typeName) throws Exception {
    	if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ACTIVITY_ONLY_TEACHER.getObj());
        }
        //保存活动
        Activity activity = new Activity();
        activity.setContent(content);
        activity.setFiles(files);
        activity.setTitle(title);
        activity.setDepartment(department);
        activity.setPublisherAccountId(accountId);
        activity.setTypeName(typeName);
        activity.setTotalScore(score);
        activity.setAddTime(LocalDateTime.now());
        activity.setEndDate(endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        activity.setUpdateTime(LocalDateTime.now());
        activity.setIsExamineFinish(true);
        activity.save();
        
        return Ret.ok();
    }

    /**
     * 修改活动
     * 不改变发布人
     */
    public Ret updateActivity(Integer userType, String title, String content, String department, String files, Integer score, Integer activityId, Date endDate, String typeName) throws Exception {        
        if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ACTIVITY_ONLY_TEACHER.getObj());
        }
        Activity activity = Activity.dao.findFirst("SELECT * FROM activity WHERE id = ? ", activityId);
        if (BeanUtil.isEmpty(activity)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NULL.getObj());
        }
        //更新数据
        activity.setContent(content);
        activity.setFiles(files);
        activity.setTitle(title);
        activity.setDepartment(department);
        activity.setTypeName(typeName);
        activity.setTotalScore(score);
        activity.setAddTime(LocalDateTime.now());
        activity.setEndDate(endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        activity.setUpdateTime(LocalDateTime.now());
        activity.update();
        
        return Ret.ok();
    }
    
    /**
     * 老师删除自己发布的活动
     */
    public Ret deleteUserPublicActivity(Integer accountId, Integer userType, Integer activityId){
    	if (userType != Const.UserType.admin) {
            return Ret.fail().set("error", EnumError.ACTIVITY_ONLY_TEACHER.getObj());
        }
    	Activity activity = Activity.dao.findFirst("SELECT id FROM activity WHERE id = ? AND publisher_account_id = ?", activityId, accountId);
    	if(BeanUtil.isNotEmpty(activity)) {
    		activity.delete();
    	}
    	return Ret.ok();
    }

    /**
     * 活动报名
     */
    public Ret signUpActivity(Integer accountId, Integer userType, String name, String clas, String mbtiPersonality, String describe, Integer activityId) throws Exception {
        Activity activity = Activity.dao.findById(activityId);
        //查询当前活动是否存在
        if (BeanUtil.isEmpty(activity)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NULL.getObj());
        }
        
        if (userType != Const.UserType.student) {
            return Ret.fail().set("error", EnumError.ACTIVITY_ONLY_STUDENT_PAR.getObj());
        }
        //查询当前用户是否已经报名
        ActivityEnroll activityEnroll = ActivityEnroll.dao.findFirst("SELECT id FROM activity_enroll WHERE student_account_id = ? AND activity_id = ?", accountId, activityId);
        if (BeanUtil.isNotEmpty(activityEnroll)) {
            return Ret.fail().set("error", EnumError.USER_HAVA_SINGN_UP_ACTIVITY.getObj());
        }
        ActivityEnroll enroll = new ActivityEnroll();
        enroll.setActivityId(activityId);
        enroll.setName(name);
        enroll.setBrief(describe);
        enroll.setMbti(mbtiPersonality);
        enroll.setClas(clas);
        enroll.setStudentAccountId(accountId);
        enroll.save();
        return Ret.ok();
    }

    /**
     * 活动参与
     *
     * @param user
     * @param files
     * @param description
     * @return
     */
    public Ret participationActivity(Integer accountId, Integer userType, String files, String description, Integer activityId) throws Exception {

        if (userType != Const.UserType.student) {
            return Ret.fail().set("error", EnumError.ACTIVITY_ONLY_STUDENT_PAR.getObj());
        }
        Activity activity = Activity.dao.findById(activityId);
        if(BeanUtil.isEmpty(activity)) {
        	return Ret.fail().set("error", EnumError.ACTIVITY_NULL.getObj());
        }
        if(LocalDateTime.now().isAfter(activity.getEndDate())) {
        	return Ret.fail().set("error", EnumError.ACTIVITY_END.getObj());
        }
        //校验当前学生是否报名
        ActivityEnroll enroll = ActivityEnroll.dao.findFirst("SELECT id FROM activity_enroll WHERE activity_id = ? AND student_account_id = ?", activityId, accountId);
        if (BeanUtil.isEmpty(enroll)) {
            return Ret.fail().set("error", EnumError.NOT_ENROLL_ACTIVITY.getObj());
        }
        //查询是否已经完成该活动
        ActivityUser activityUser = ActivityUser.dao.findFirst("SELECT * FROM activity_user WHERE activity_id = ? AND student_account_id = ?", activityId, accountId);
        if (BeanUtil.isEmpty(activityUser)) {
            activityUser = new ActivityUser();
            activityUser.setActivityId(activityId);
            activityUser.setFiles(files);
            activityUser.setDescription(description);
            activityUser.setStudentAccountId(accountId);
            activityUser.setUploadTime(LocalDateTime.now());
            activityUser.save();
            //固定加三分
            Record record = Redis.use().hget(Const.user.AccountIdInfo, accountId);
            UserUtil.addScoreForStu(record.getInt("id"), 3, Const.addMarkEventType.ACTIVITY_PARTAKE, activity.getId());
        }else {
        	Integer evaluateAccountId = activityUser.getEvaluateAccountId();
	        //判断当前活动审核状态
	        if (evaluateAccountId != null) {
	            return Ret.fail().set("error", EnumError.ACTIVITY_FILES_HAVE_EVALUATE.getObj());
	        }
	        activityUser.setFiles(files);
	        activityUser.setDescription(description);
	        activityUser.setUploadTime(LocalDateTime.now());
	        activityUser.setUpdateTime(LocalDateTime.now());
	        activityUser.update();
        }
        //修改活动完成状态
        activity.setIsExamineFinish(false);
    	activity.update();
        
        return Ret.ok();
    }

    /**
     * 发表心得
     *
     * @param user
     * @param activityId
     * @param content
     * @return
     * @throws Exception
     */
    @Before(Tx.class)
    public Ret publishRealize(Integer accountId, Integer activityId, String content, Boolean isShare) throws Exception {

        //查询当前活动参与情况
        ActivityUser activityUser = ActivityUser.dao.findFirst("SELECT * FROM activity_user WHERE activity_id = ? AND student_account_id = ?", activityId, accountId);
        if (BeanUtil.isEmpty(activityUser)) {
            return Ret.fail().set("error", EnumError.NOT_PAR_ACTIVITY.getObj());
        }
        Integer evaluateAccountId = activityUser.getEvaluateAccountId();
        if (evaluateAccountId == null) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NOT_EXAMIN.getObj());
        }
        activityUser.setRealizeContent(content);
        activityUser.setRealizeTime(LocalDateTime.now());
        if (isShare) {
            //添加原创发布
            CampusShareOriginal campusShareOriginal = new CampusShareOriginal();
            campusShareOriginal.setContent(content);
            campusShareOriginal.setActivityId(activityId);
            campusShareOriginal.setUserAccountId(accountId);
            campusShareOriginal.save();
        }
        activityUser.update();
        return Ret.ok();
    }

    /**
     * 老师查询所有活动中待审核的数量
     */
    public Ret getWaitExamineTotal() throws Exception {
    	int total = 0;
        List<Activity> activitieList = Activity.dao.find("SELECT id,title FROM activity WHERE is_examine_finish = 0 ");//AND JSON_CONTAINS(appraise_account_ids, ?)
    	for(Activity activitie : activitieList) {
    		Integer num = Db.queryInt("SELECT COUNT(*) FROM activity_user WHERE activity_id = ? AND evaluate_account_id IS NULL", activitie.getId());
    		total = total + num;
    	}
        return Ret.ok("total", total);
    }
    
    /**
     * 老师查询所有做某个活动的学生以及统计数量
     */
    public Ret getActivityAllStudentList(Integer activityId) throws Exception {
    	Activity activity = Activity.dao.findFirst("SELECT id FROM activity WHERE id = ?", activityId);
        if (BeanUtil.isEmpty(activity)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NULL.getObj());
        }
    	List<ActivityEnroll> waitList = new ArrayList<ActivityEnroll>();
    	List<ActivityEnroll> alreadyList = new ArrayList<ActivityEnroll>();
    	List<ActivityEnroll> onlyEnrollList = new ArrayList<ActivityEnroll>();
    	List<ActivityEnroll> activityEnrollList = ActivityEnroll.dao.find("SELECT ae.student_account_id studentAccountId,s.`name`,s.avatarUrl,(SELECT wd.dept_name_cn FROM wl_department wd WHERE wd.org_class_id = s.clasId) className FROM activity_enroll ae LEFT JOIN student s ON ae.student_account_id = s.accountId WHERE ae.activity_id = ?", activityId);
    	for(ActivityEnroll activityEnroll : activityEnrollList) {
    		ActivityUser activityUser = ActivityUser.dao.findFirst("SELECT * FROM activity_user WHERE student_account_id = ? AND activity_id = ?", activityEnroll.getInt("studentAccountId"), activityId);
    		if(BeanUtil.isEmpty(activityUser)) {
    			onlyEnrollList.add(activityEnroll);
    		}else {
    			if(activityUser.getEvaluateAccountId() == null) {
    				waitList.add(activityEnroll);
    			}else {
    				alreadyList.add(activityEnroll);
    			}
    		}
    	}
		return Ret.ok("waitList", waitList).set("alreadyList", alreadyList).set("onlyEnrollList", onlyEnrollList);
        
    }
    
    /**
     * 老师查询某个活动的每个学生完成的具体情况
     */
    public Ret getActivityStudentList(Integer state, Integer activityId) throws Exception {
        Activity activity = Activity.dao.findFirst("SELECT id,title,end_date FROM activity WHERE id = ?", activityId);
        if (BeanUtil.isEmpty(activity)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NOT_PUBLISHED_BY_YOU.getObj());
        }
        List<Record> activityUsers;
        if (state == 0) {
            activityUsers = Db.find("SELECT au.*,ae.mbti,ae.brief,ae.clas FROM activity_user au INNER JOIN activity_enroll ae ON au.activity_id = ae.activity_id AND au.student_account_id = ae.student_account_id WHERE au.activity_id = ? AND au.evaluate_account_id IS NULL ORDER BY id DESC", activityId);
        } else {
            activityUsers = Db.find("SELECT au.*,ae.mbti,ae.brief,ae.clas FROM activity_user au INNER JOIN activity_enroll ae ON au.activity_id = ae.activity_id AND au.student_account_id = ae.student_account_id WHERE au.activity_id = ? AND au.evaluate_account_id IS NOT NULL ORDER BY id DESC", activityId);
        }
        List<Record> list = activityUsers.stream().map(activityUser -> {
            Record record = Redis.use().hget(Const.user.AccountIdInfo, activityUser.getInt("student_account_id"));
            Student o = Redis.use().get(Const.user.Student + record.getInt("id"));
            activityUser.put("name", o.getName());
            activityUser.put("sex", o.getSex());
            activityUser.put("pic", o.getAvatarUrl());
            activityUser.put("accountId", o.getAccountId());
            return activityUser;
        }).collect(Collectors.toList());
        return Ret.ok().set("stuActivityList", list).set("activity", activity);
    }

    /**
     * 活动审核
     */
    @Before(Tx.class)
    public Ret examineActivity(Integer accountId, Integer userType, Integer score, String content, Integer evaluation, Integer activityUserId, String medalName) throws Exception {

        ActivityUser activityUser = ActivityUser.dao.findById(activityUserId);
        if (BeanUtil.isEmpty(activityUser)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_USER_NOT_EXIST.getObj());
        }
        Activity activity = Activity.dao.findFirst("SELECT id,title FROM activity WHERE id = ?", activityUser.getActivityId());
        if (BeanUtil.isEmpty(activity)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NOT_PUBLISHED_BY_YOU.getObj());
        }
        activityUser.setEvaluateAccountId(accountId);
        activityUser.setEvaluation(evaluation);
        activityUser.setEvaluateContent(content);
        activityUser.setEvaluateTime(LocalDateTime.now());
        activityUser.setScoreTeacher(score);
        //先删除勋章
        Db.delete("DELETE FROM medal_user WHERE account_id = ? AND activity_id = ?", activityUser.getStudentAccountId(), activity.getId());
        //添加勋章
        if(StrUtil.isNotBlank(medalName)) {
        	Medal medal = Medal.dao.findFirst("SELECT * FROM medal_user WHERE medal_name = ?", medalName);
	        if(BeanUtil.isEmpty(medal)) {
	        	medal = new Medal();
	        	medal.setName(medalName);
	        	medal.setAddAccountId(accountId);
	        	medal.setAddTime(LocalDateTime.now());
	        	medal.save();
	        }
	        activityUser.setMedalName(medalName);
	        
	        MedalUser medalUser = new MedalUser();
        	medalUser.setAccountId(activityUser.getStudentAccountId());
        	medalUser.setMedalName(medalName);
        	medalUser.setIssueAccountId(accountId);
        	medalUser.setAddTime(LocalDateTime.now());
        	medalUser.setActivityId(activity.getId());
        	medalUser.save();
        }
        //保存修改
        activityUser.update();
        //修改活动完成状态
        Integer undoneActivityUserCount = Db.queryInt("SELECT COUNT(*) FROM activity_user WHERE activity_id = ? AND evaluate_account_id IS NULL", activity.getId());
        if(undoneActivityUserCount == 0) {
        	activity.setIsExamineFinish(true);
        	activity.update();
        }
        Record record = Redis.use().hget(Const.user.AccountIdInfo, activityUser.getStudentAccountId());
        //删除积分
        UserUtil.addScoreForStuDeleteLog(record.getInt("id"), Const.addMarkEventType.ACTIVITY, activityUser.getId());
        //添加积分
        UserUtil.addScoreForStu(record.getInt("id"), score, Const.addMarkEventType.ACTIVITY, activityUser.getId());
        //删除轨迹
        Db.delete("DELETE FROM student_trajectory WHERE user_account_id = ? AND task_id = ? AND task_type = ?", activityUser.getStudentAccountId(), activity.getId(), Const.taskType.ACTIVITY);
        //如果三星自动进入轨迹
        if (score >= 3) {
        	StudentTrajectory studentTrajectory = new StudentTrajectory();
            studentTrajectory.setTaskId(activityUser.getActivityId());
            studentTrajectory.setTaskType(Const.taskType.ACTIVITY);
            studentTrajectory.setUserAccountId(activityUser.getStudentAccountId());
            studentTrajectory.setContent(activity.getTitle());
            studentTrajectory.save();
        }
        return Ret.ok();
    }

    /**
     * 查询某个活动的学生排名
     */
    public Ret getActivityUserRanking(Integer accountId, Integer activityId, Boolean isAdmin) throws Exception {
    	Ret ret = Ret.ok();
    	if(isAdmin) {
    		Activity activity = Activity.dao.findFirst("SELECT id FROM activity WHERE id = ?", activityId);
	        if (BeanUtil.isEmpty(activity)) {
	            return Ret.fail().set("error", EnumError.ACTIVITY_NOT_PUBLISHED_BY_YOU.getObj());
	        }
	        //查询发布状态
	    	Record record = Db.findFirst("SELECT id FROM activity_user_ranking_public WHERE activity_id = ?", activityId);
	    	ret.set("isPublic", BeanUtil.isNotEmpty(record));
    	}else {
    		ActivityUserRankingPublic activityUserRankingPublic = ActivityUserRankingPublic.dao.findFirst("SELECT * FROM activity_user_ranking_public WHERE activity_id = ?", activityId);
    		if(BeanUtil.isEmpty(activityUserRankingPublic)) {
    			return Ret.fail().set("error", EnumError.ACTIVITY_NOT_PUBLIC_RANKING.getObj());
    		}
    	}
    	List<ActivityUser> activityUserList = ActivityUser.dao.find("SELECT id,student_account_id,evaluation,score_teacher,medal_name FROM activity_user WHERE activity_id = ? ORDER BY evaluation DESC", activityId);
    	for(ActivityUser activityUser : activityUserList) {
    		Record record = Redis.use().hget(Const.user.AccountIdInfo, activityUser.getStudentAccountId());
            Student o = Redis.use().get(Const.user.Student + record.getInt("id"));
            activityUser.put("name", o.getName());
    	}
    	ret.set("activityUserRanking", activityUserList);
    	
    	return ret;
    }
    
    /**
     * 首页活动排行Banner
     */
    public Ret getActivityUserRankingBanner() throws Exception {
    	
    	List<ActivityUserRankingPublic> activityUserRankingPublicList = ActivityUserRankingPublic.dao.findAll();
    	for(ActivityUserRankingPublic activityUserRankingPublic : activityUserRankingPublicList) {
    		Activity activity = Activity.dao.findFirst("SELECT type_name FROM activity WHERE id = ?", activityUserRankingPublic.getActivityId());
    		if(BeanUtil.isEmpty(activity)) {
    			continue;
    		}
    		activityUserRankingPublic.put("typeName", activity.getTypeName());
    		
    		List<ActivityUser> returnActivityUserList = new ArrayList<ActivityUser>();
    		List<ActivityUser> activityUserList = ActivityUser.dao.find("SELECT id,student_account_id,evaluation,score_teacher,medal_name FROM activity_user WHERE activity_id = ? ORDER BY evaluation DESC LIMIT 5", activityUserRankingPublic.getActivityId());//最多获取前五
    		if(activityUserList.size() > 0) {
    			//按名次排序赛选
        		int rank = 1;
        		Integer evaluation = activityUserList.get(0).getEvaluation();
        		if(evaluation != null) {
        			for(ActivityUser activityUser : activityUserList) {
        				int thisEvaluation = activityUser.getEvaluation();
        				activityUser.put("rank", rank);
        				if(evaluation > thisEvaluation) {
	            			if(rank >= 3){
	            				break;
	            			}
	            			rank = rank + 1;
	            		}
        				returnActivityUserList.add(activityUser);
	            		evaluation = thisEvaluation;
	            	}
	        		
        		}
    		}
    		
    		for(ActivityUser activityUser : returnActivityUserList) {
        		Record record = Redis.use().hget(Const.user.AccountIdInfo, activityUser.getStudentAccountId());
                Student o = Redis.use().get(Const.user.Student + record.getInt("id"));
                activityUser.put("name", o.getName());
                activityUser.put("sex", o.getSex());
                activityUser.put("pic", o.getAvatarUrl());
                activityUser.put("accountId", o.getAccountId());
        	}
    		
    		activityUserRankingPublic.put("returnActivityUserList", returnActivityUserList);
    	}
    	return Ret.ok("activityUserRankingBanner", activityUserRankingPublicList);
    }
    
    
    /**
     * 发布/撤销活动排名结果
     */
    public Ret publicActivityUserRanking(Integer accountId, Integer activityId) throws Exception {
    	Activity activity = Activity.dao.findFirst("SELECT id,end_date FROM activity WHERE id = ? ", activityId);
        if (BeanUtil.isEmpty(activity)) {
            return Ret.fail().set("error", EnumError.ACTIVITY_NOT_PUBLISHED_BY_YOU.getObj());
        }
        ActivityUserRankingPublic activityUserRankingPublic = ActivityUserRankingPublic.dao.findFirst("SELECT * FROM activity_user_ranking_public WHERE activity_id = ?", activityId);
    	if(BeanUtil.isEmpty(activityUserRankingPublic)) {
    		//判断勋章是否相同
    		List<Integer> medalNameList = Db.query("SELECT medal_name FROM activity_user WHERE activity_id = ? AND medal_name IS NOT NULL GROUP BY medal_name", activityId);
    		if(medalNameList.size() > 1) {
    			return Ret.fail().set("error", EnumError.MEDAL_NAME_UNLIKE.getObj());
    		}
    		//判断截至时间
    		if(!activity.getEndDate().toLocalDate().isAfter(LocalDate.now())) {
    			return Ret.fail().set("error", EnumError.ACTIVITY_FINISH.getObj());
    		}
    		activityUserRankingPublic = new ActivityUserRankingPublic();
    		activityUserRankingPublic.setActivityId(activityId);
    		activityUserRankingPublic.setAddTime(LocalDateTime.now());
    		activityUserRankingPublic.setPublicAccountId(accountId);
    		activityUserRankingPublic.save();
    	}else {
    		activityUserRankingPublic.delete();
    	}
    	return Ret.ok();
    }
    
    /**
     * 获取用户勋章列表
     */
    public Ret getUserMedalList(Integer accountId) throws Exception {
    	List<MedalUser> medalUserList = MedalUser.dao.find("SELECT * FROM medal_user WHERE account_id = ?", accountId);
    	return Ret.ok("medalUserList", medalUserList);
    }
    
    /**
     * 获取勋章列表
     */
    public Ret getMedalList() throws Exception {
    	List<Medal> medalList = Medal.dao.findAll();
    	return Ret.ok("medalList", medalList);
    }
    

}
